using System;
using System.Collections.Generic;
using System.Linq;
using VoiceAd.Models;
using System.Data.Linq.SqlClient;

namespace VoiceAd.DAL
{
    public class DistrictRepository : IDistrictRepository, IDisposable
    {
        private dbVoiceAdDataContext context = new dbVoiceAdDataContext();

        public DistrictRepository(dbVoiceAdDataContext db)
        {
            this.context = db;
        }

        public IEnumerable<tblDistrict> GetListDistricts()
        {
            return context.tblDistricts.ToList();
        }

        public IEnumerable<tblDistrict> GetListSearchDistricts(string DistrictName)
        {
            IEnumerable<tblDistrict> lst = from a in context.tblDistricts
                                           where SqlMethods.Like(a.DistrictName, "%" + DistrictName + "%")
                                           select a;

            return lst;
            //return context.tblDistricts.ToList();
        }

        public IEnumerable<tblDistrict> GetListDistricts(int idArea)
        {
            return context.tblDistricts.Where(x => x.tblProvince.tblArea.Id == idArea).OrderByDescending(x => x.ProvinceId).ToList();
        }

        public IEnumerable<tblDistrict> GetByProvinceId(int lProvinceID)
        {
            return context.tblDistricts.Where(x => x.ProvinceId == Convert.ToInt32(lProvinceID)).ToList();
        }

        public tblDistrict GetDistrictById(int id)
        {
            return context.tblDistricts.Where(x => x.Id == id).FirstOrDefault();
        }

        public void InsDistrict(tblDistrict tbldistrict)
        {
            context.tblDistricts.InsertOnSubmit(tbldistrict);
            context.SubmitChanges();
        }

        public void UpdDistrict(tblDistrict tbldistrict)
        {
            tblDistrict obj = context.tblDistricts.Where(x => x.Id == tbldistrict.Id).First();
            obj.ProvinceId = tbldistrict.ProvinceId;
            obj.DistrictName = tbldistrict.DistrictName;
            context.SubmitChanges();
        }

        public void DelDistrict(int id)
        {
            tblDistrict obj = context.tblDistricts.Single(x => x.Id == id);
            context.tblDistricts.DeleteOnSubmit(obj);
            context.SubmitChanges();
        }

        private bool disposed = false;

        protected virtual void Dispose(bool disposing)
        {
            if (!this.disposed)
            {
                if (disposing)
                {
                    context.Dispose();
                }
            }
            this.disposed = true;
        }

        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }
    }
}
